import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'interface.dart';
import 'model.dart';

class Swapi implements IStarWarsApi {
  final _baseUrl = 'https://swapi.co/api';

  Future<dynamic> _getData(String url) async {
    var response = await http.get(url);
    var data = json.decode(response.body);
    return data;
  }

  Future<List<Film>> getFilms() async {
    var data = await _getData("$_baseUrl/films");
    List<dynamic> filmdata = data["results"];
    List<Film> films = filmdata
        .map((f) => Film(
              title: f["title"],
              openingCrawl: f["opening_crawl"],
              director: f["director"],
              producor: f["productor"],
              releaseDate: DateTime.parse(f["release_date"]),
            ))
        .toList();
    return films;
  }

  Future<List<Character>> getCharacters() async {
    var data = await _getData("$_baseUrl/people");
    List<dynamic> chactarsData = data["results"];
    List<Character> charactars = chactarsData
        .map((f) => Character(
              name: f['name'],
              birthYear: f['birth_year'],
              gender: f['gender'],
              height: int.parse(f['height']),
              eyeColor: f['eye_color'],
            ))
        .toList();
    return charactars;
  }

  Future<List<Planet>> getPlanets() async {
    var data = await _getData("$_baseUrl/planets");
    List<dynamic> plantdata = data["results"];
    List<Planet> plants = plantdata
        .map((f) => Planet(
              name: f['name'],
              climate: f['climate'],
              terrain: f['terrain'],
              diameter: int.parse(f['diameter']),
              gravity: f['gravity'],
              population: f['population'],
            ))
        .toList();
    return plants;
  }
}
